﻿using System;
using Castle.ActiveRecord;
using NHibernate.Expression;
using Hadlow.Jobvertizer.Models;

namespace Hadlow.Jobvertizer.Repositories
{
    public class LocationRepository : ActiveRecordBase<Location>, ILocationRepository
    {
        public Location GetTopLevelLocation()
        {
            ICriterion parentNullCriterion = Expression.IsNull("Parent");
            Location topLevelLocation = FindFirst(parentNullCriterion);

            if (topLevelLocation == null)
            {
                throw new ApplicationException("There is no top level Location in the database. " +
                    "I.e. a Location record with a NULL ParentId.");
            }

            return topLevelLocation;
        }

        public Location GetForId(int id)
        {
            return FindByPrimaryKey(id);
        }
    }
}
